import log from '../logger'
import {WaitUpState} from "../interfaces";
import readyState from "./0ready";
import weightState from "./2weight";
import state from "./state";
import controller from "../controller";
import weighter from "../weight";

export class WaitUpStateImpl implements WaitUpState {
    name = "WaitUpState"

    WAITUPTIMEOUT = 60;
    CHANGESTATETIMEOUT = 10;

    closeWaitUpTimer: NodeJS.Timeout
    toReadyStateTimer: NodeJS.Timeout

    init(): void {
        controller.openUpInout(state.inout)
        this.closeWaitUpTimer = setTimeout(() => {
            if (state.stateContext.name === 'WaitUpState') {
                log.info('等待车辆上磅超时，关闭道闸')
                controller.closeWaitUpTimeout(state.inout)
                // 先关闭道闸，10秒后再修改状态，解决关闭道闸同时上磅
                this.toReadyStateTimer = setTimeout(() => {
                    if (state.stateContext.name === 'WaitUpState') {
                        log.info('等待车辆上磅超时，改变状态')
                        state.stateContext = readyState;
                    }
                }, 1000 * this.CHANGESTATETIMEOUT)
            }
        }, 1000 * this.WAITUPTIMEOUT)
    }

    leave(): void {
    }

    plate(vehicleNumber: string, inout: string): void {
    }

    active(R: boolean[]): void {
    }

    weight_data(weight: number, wen: boolean): void {
        if (weight > 0.5) {
            clearTimeout(this.closeWaitUpTimer);
            this.closeWaitUpTimer = undefined;
            clearTimeout(this.toReadyStateTimer);
            this.toReadyStateTimer = undefined;
            state.stateContext = weightState;
            weighter.emit('weight_data', weight, wen);
            // 持久化状态，过磅中可以重启系统
            state.writeState();
        }
    }

    driverRequest(type: string): void {
    }

    do_weigh(weight: number, deductionWeight: number): void {
    }

}

const waitUpState = new WaitUpStateImpl();
export default waitUpState;